package top.ivansong.cxf.registry.util;

import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import com.alibaba.fastjson.JSON;
import top.ivansong.cxf.registry.api.ServiceBeanInfo;

public class ServiceBeanSerializeUntil {
	
    private static Map<String, String> specialCharMap = new HashMap<>();
   
    static {
    	specialCharMap.put("\\", "#5C");
    	specialCharMap.put("/", "#2F");
    }
    
    private ServiceBeanSerializeUntil() {}
    
	public static String encoded(ServiceBeanInfo bean) {
		String res = JSON.toJSONString(bean);
		Set<String> keys = specialCharMap.keySet();
		for (String string : keys) {
			if (res.contains(string)) {
				res = res.replace(string, specialCharMap.get(string));
			}
		}
		return res;
	}

	public static String encodedUrl(String beanUrl) {
		Set<String> keys = specialCharMap.keySet();
		for (String string : keys) {
			if (beanUrl.contains(string)) {
				beanUrl = beanUrl.replace(string, specialCharMap.get(string));
			}
		}
		return beanUrl;
	}

	public static ServiceBeanInfo decode(String bean) {
		String res = new String(bean);
		Set<Entry<String, String>> entries = specialCharMap.entrySet();
		for (Entry<String, String> entry : entries) {
			if (bean.contains(entry.getValue())) {
				res = bean.replace(entry.getValue(), entry.getKey());
			}
		}
		return JSON.parseObject(res, ServiceBeanInfo.class);
	}
}
